import { hexMD5 } from './md5.js'
const md5Key = '889ebb98e2667df399ce17bc01037aac';

export const post = (url, body = {}) => {
  let now = new Date().getTime()
  let sign = md5(now, body)
  return new Promise((resolve, reject) => {
    wx.request({
      url: url,
      data: body,
      method: 'POST',
      dataType: 'json',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded',
        // 'Sign': sign,
        'Time': now
      },
      success (res) {
        if(res.statusCode == 200){
          resolve(res.data)
        } else {
          reject(res.data)
        }
      },
      fail(res) { reject(res) }
    })  
  })
}

export const get = (url, body = {}) => {
  return new Promise((resolve, reject) => {
    wx.request({
      url: url,
      data: body,
      method: 'GET',
      success(res) {
        if (res.statusCode == 200) {
          resolve(res.data)
        } else {
          reject(res.data)
        }
      },
      fail(res) { reject(res) }
    })
  })
}

function md5 (now, body) {
  let obj = Object.assign({}, body, {
    key: md5Key,
    time: now
  })
  let array = []
  let keyArray = []
  for (let key in obj) {
    keyArray.push(key)
  }
    keyArray.sort()
  for (let key of keyArray) {
    array.push(obj[key])
  }
  return hexMD5(array.join(''))
}
